/* 定义一组常量 */
var MessageType = function() {
};

var GameModeType = function() {
};
GameModeType.MODE_TYPE_NORMAL = 1;
GameModeType.MODE_TYPE_MATCH = 2;
GameModeType.MODE_TYPE_BOSS = 3;
GameModeType.MODE_TYPE_BEAN_FUN_BATTLE = 4;
GameModeType.MODE_TYPE_COMPETITION = 5;

// 服务端 向 客户端 发送的消息类型
/** 错误 */
MessageType.ERROR = 10000000;
/** 选位成功，某人选择了某个位置 */
MessageType.SIT_SUCC = 10000001;
/** 选位失败 */
MessageType.SIT_FAILED = 10000002;
/** 服务器已收到，某玩家，准备好了 */
MessageType.READY_SUCC = 10000003;
/** 发牌 */
MessageType.DEAL_CARD = 10000004;
/** 询问用户是否抢地主 */
MessageType.ASK_GRAB_LANDLORD = 10000005;
/** 开始出牌了 */
MessageType.START_OUT_CARD = 10000006;
/** 出牌失败 */
MessageType.OUT_CARD_FAILED = 10000007;
/** 轮到某人出牌了 */
MessageType.TURN_TO_OUT_CARD = 10000008;
/** 游戏结束 */
MessageType.GAME_OVER = 10000009;
/** 聊天消息 */
MessageType.CHAT_MESSAGE = 10000010;
/** 某用户网络连接中断 */
MessageType.NET_INTERRUPTED = 10000011;
/** 进入托管状态 */
MessageType.MANAGED_SUCC = 10000012;
/** 取消托管状态 */
MessageType.UNMANAGED_SUCC = 10000013;
/** 某人出牌了 */
MessageType.OUT_CARD_SUCC = 10000014;
/** 出牌提示成功 */
MessageType.OUTCARD_SUGGESTION_SUCC = 10000015;
/** 询问农民是否翻倍（是否踢） */
MessageType.ASK_FARMER_DOUBLE = 10000016;
/** 农民选择的结果，是否翻倍（是否踢） */
MessageType.RESULT_FARMER_DOUBLE = 10000017;
/** 询问地主是否翻倍（是否拉） */
MessageType.ASK_LANDLORD_DOUBLE = 10000018;
/** 地主选择的结果，是否翻倍（是否拉） */
MessageType.RESULT_LANDLORD_DOUBLE = 10000019;
/** 抢地主结果 */
MessageType.RESULT_GRAB_LANDLORD = 10000020;
/** 需要重连 */
MessageType.NEED_RECONNECT = 10000021;
/** 不需要重连 */
MessageType.NOT_NEED_RECONNECT = 10000022;
/** 某玩家离开了 */
MessageType.STAND_SUCC = 10000023;
/** 系统广播 */
MessageType.SYSTEM_MSG = 10000024;
/** 被踢出房间 */
MessageType.KICKED_OUT = 10000025;
/** 活动送乐豆 */
MessageType.REWARD_BEAN_FUN = 10000026;
/** 进入房间成功 */
MessageType.GO_IN_ROOM_SUCC = 10000027;
/** 进入房间失败 */
MessageType.GO_IN_ROOM_FAILED = 10000028;
/** 系统单点广播 */
MessageType.PERSONAL_MSG = 10000029;
/** 某人重连成功 */
MessageType.RECONNECT_SUCC = 10000030;
/** 收消息 强行退出 */
MessageType.GET_FORCE_OUT = 10000031;
/** 都准备好了 */
MessageType.ALL_READY = 10000033;
/** 开局成功 */
MessageType.OPEN_GAME_SUCC = 10000034;
/** 使用道具成功 */
MessageType.USE_ITEM_SUCC = 10000035;
/** 使用道具失败 */
MessageType.USE_ITEM_FAIL = 10000036;
/** 报名人数 */
MessageType.USE_SIGNUP_NUMBER = 10000037;
/** 比赛结果 */
MessageType.USE_GAME_OVER = 10000038;

/** 开启第二号房间 */
MessageType.OPENING_ROOM_102 = 10000102;
/** 开启第三号房间 */
MessageType.OPENING_ROOM_103 = 10000103;
/** 开启第四号房间 */
MessageType.OPENING_ROOM_104 = 10000104;
/** 开启第五号房间 */
MessageType.OPENING_ROOM_105 = 10000105;

/** 开启第二号Boss */
MessageType.OPENING_BOOS_102 = 10000112;
/** 开启第三号Boss */
MessageType.OPENING_BOOS_103 = 10000113;

/** 开启初级比赛场 */
MessageType.OPENING_COMPETITION_101 = 10000121;
/** 启中级比赛场 */
MessageType.OPENING_COMPETITION_102 = 10000122;
/** 开启高级比赛场 */
MessageType.OPENING_COMPETITION_103 = 10000123;

/** 开启乐斗场 */
MessageType.OPENING_BEANFUN_BATTLE = 10000131;

// 客户端向服务端发送的消息类型
/** 选位 */
MessageType.SIT = 20000001;
/** 离开桌子 */
MessageType.STAND = 20000002;
/** 准备好了 */
MessageType.READY = 20000003;
/** 抢地主 */
MessageType.GRAB_LANDLORD = 20000004;
/** 不出牌 */
MessageType.NOT_OUT_CARD = 20000005;
/** 出牌 */
MessageType.OUT_CARD = 20000006;
/** 聊天消息 */
MessageType.SEND_CHAT_MESSAGE = 20000007;
/** 进入托管状态 */
MessageType.REQUEST_MANAGED = 20000008;
/** 取消托管状态 */
MessageType.REQUEST_UNMANAGED = 20000009;
/** 出牌提示 */
MessageType.REQUEST_OUTCARD_SUGGESTION = 20000010;
/** 农民加倍（踢） */
MessageType.FARMER_DOUBLE = 20000011;
/** 地主加倍（反踢） */
MessageType.LANDLORD_DOUBLE = 20000012;
/** 出牌超时 */
MessageType.TIME_OUT_ON_OUT_CARDS = 20000013;
/** 某人强行退出 */
MessageType.FORCE_OUT = 20000014;
/** 开局 */
MessageType.OPEN_GAME = 20000016;
/** 使用道具 */
MessageType.USE_ITEM= 20000017;

// 打牌的状态
var Desk = function() {
};
/** 没有开始 */
Desk.STATE_NOT_START = 1;
/** 准备状态 */
Desk.STATE_ON_WAITING_OPEN_GAME = 2;
/** 正在抢地主 */
Desk.STATE_ON_GRAB_LANDLORD = 3;
/** 正在加倍 */
Desk.STATE_ON_DOUBLE = 4;
/** 正在出牌 */
Desk.STATE_ON_OUT_CARD = 5;
/** 游戏结束 */
Desk.STATE_ON_OUT_GAMEOVER = 6;

var my;
var left;
var right;
var dataStorage = new DataStorage();
function initGame() {
	my = new MyPoker("");
	dataStorage.reset();
}

/**
 * 服务器往浏览器发送消息的处理函数
 * 
 * @param event
 */
function handleJsonResult(event) {
	console.log("新消息 --> " + event.data);
	// 将返回的json数据序列化成js对象
	var jsObject = JSON.parse(event.data);
	
	switch (jsObject.type) {
	// 入桌成功，即选座成功
	case MessageType.SIT_SUCC:
		console.log(jsObject.playerId + "-->入桌成功!");
		//存储比赛类型
		dataStorage.set(OtherThing.gameModeType, jsObject.gameModeType);
		// 更新牌桌顶部“基分”
		player.setBaseScore(jsObject.baseScore);
		dataStorage.set(OtherThing.baseScore, jsObject.baseScore);
		if (jsObject.playerId == getMyPlayerId()) {
			my.name = jsObject.playerId;
			// 存储当前用户信息
			dataStorage.set(MyOwner.playerId, jsObject.playerId);
			dataStorage.set(MyOwner.sit, jsObject.sit); // 座位号
			my.goin();
			my.button().ready();
			
			// gameModeType游戏模式
			if (jsObject.gameModeType == GameModeType.MODE_TYPE_MATCH) {// 2为比赛场
				toolBar.showGameRankInfo();// 显示打满局数区域
				toolBar.setGameRankInfo(jsObject.myMatchCount,
						jsObject.maxMatchCount);// 显示数值
			}
		}

		var playersInfo = jsObject.deskState.playersInfo;
		for ( var i = 0; i < playersInfo.length; i++) {
			
			var nickName = playersInfo[i].roleName;
			var chipsCount = playersInfo[i].beanFunCount;
			var role = playersInfo[i].roleResourceName;
			var star = playersInfo[i].star;
			var candy = playersInfo[i].candy;
			var score = playersInfo[i].score;
			if(jsObject.gameModeType == GameModeType.MODE_TYPE_MATCH){
				chipsCount = playersInfo[i].matchChipsCount;
			}
			
			if (playersInfo[i].playerId == getMyPlayerId()) {
				// 显示自身的昵称和乐豆数
				player.goin("my", {
					"name" : nickName,
					"dou" : chipsCount,
					"role":role,
					"star":star,
					"candy":candy,
					"score":score
				
				});
				player.setInfo().peopleHead("my",role,1);
				
			} else {
				if (isOnMyRight(getMySit(), playersInfo[i].sit)) {
					// 显示右边玩家的昵称和乐豆数
					player.goin("right", {
						"name" : nickName,
						"dou" : chipsCount,
						"role":role,
						"star":star,
						"candy":candy,
						"score":score
					
					});
					player.setInfo().peopleHead("right",role,1);
					console.log("right isReady = " + playersInfo[i].isReady);
					if (playersInfo[i].isReady) {
						player.ready("right");
					}
					// 存储玩家右手边的用户信息
					dataStorage.set(RightPlayer.playerId,
							playersInfo[i].playerId);
					dataStorage.set(RightPlayer.sit, playersInfo[i].sit);
				} else {
					// 显示左边玩家的昵称和乐豆数
					player.goin("left", {
						"name" : nickName,
						"dou" : chipsCount,
						"role":role,
						"star":star,
						"candy":candy,
						"score":score
						
					});
					player.setInfo().peopleHead("left",role,1);
					console.log("left isReady = " + playersInfo[i].isReady);
					if (playersInfo[i].isReady) {
						player.ready("left");
					}
					// 存储玩家左手边的用户信息
					dataStorage.set(LeftPlayer.playerId,
							playersInfo[i].playerId);
					dataStorage.set(LeftPlayer.sit, playersInfo[i].sit);
				}
			}
		}

		break;
	// 坐下失败，即选座失败
	case MessageType.SIT_FAILED:
		/*$().alert({
			"content" : "网络不稳定，请稍后重试"
		});*/
		player.systemMsg("text-netNoStable");
		window.location.href = getServiceURL() + "/index.jsp?"
				+ (new Date()).getTime();
		break;
	// 某玩家离开了
	case MessageType.STAND_SUCC:
		if (dataStorage.get(LeftPlayer.playerId) == jsObject.playerId) {
			player.hideInfo().all("left");
		} else {
			player.hideInfo().all("right");
		}
		break;

	// 准备好了
	case MessageType.READY_SUCC:
		var playerIdOfMsgSender = jsObject.playerId;
		if (playerIdOfMsgSender === getMyPlayerId()) {
			player.ready("my");
			my.button().clear();
		} else {
			if (playerIdOfMsgSender === dataStorage.get(RightPlayer.playerId)) {
				player.ready("right");
			} else if (playerIdOfMsgSender === dataStorage
					.get(LeftPlayer.playerId)) {
				player.ready("left");
			}
		}
		break;
		
	// 3个人准备
	case MessageType.ALL_READY:
		console.log( "-->3个人准备!");
		player.hideOkMsg(); // 隐藏“准备好了”手势
		my.button().props(function(){
			openGame();
			my.button().clear();
		});
		break;
		
		// 开局成功
	case MessageType.OPEN_GAME_SUCC:
		console.log( "-->开局成功!");
	
		break;

	// 发牌
	case MessageType.DEAL_CARD:
		
		// isRedealCards为重新发牌参数
		if (jsObject.isRedealCards) {
			//player.msg("my", "text-noGrab");
			player.systemMsg("text-noGrab");
		}
		var cardsArr = jsObject.cards.split("-");
		my.get(cardsArr); // 显示发牌特效；
		if (jsObject.playerId == getMyPlayerId()) { // 只有一个人先抢地主
			gameOnGrabLandLord(3); // 延时显示“抢地主”按钮
		}

		// 设置牌数,发完牌后，每人17张
		player.setInfo().pokeyNum("left", 17);
		player.setInfo().pokeyNum("right", 17);
		break;

	// 询问用户是否抢地主
	case MessageType.ASK_GRAB_LANDLORD:
		// 更新牌桌顶部“基分”
		player.setBaseScore(jsObject.baseScore);
		askGrabLandlord(jsObject.playerId, jsObject.grabLandlordBetMin);
		break;

	// 抢地主结果
	case MessageType.RESULT_GRAB_LANDLORD:
		console.log("抢地主结果");
		// 更新牌桌顶部“基分”
		player.setBaseScore(jsObject.baseScore);
		var bottomCards = jsObject.cards.split("-");

		// 底牌存储
		dataStorage.set(OtherThing.bottomCards, bottomCards);
		setResultOfGrabLandlord(jsObject.playerId);

		var cardNumberOfLeft = 17;
		var cardNumberOfRight = 17;
		if (dataStorage.get(LeftPlayer.playerId) == jsObject.playerId) {
			cardNumberOfLeft = 20;
		} else if (dataStorage.get(RightPlayer.playerId) == jsObject.playerId) {
			cardNumberOfRight = 20;
		}

		setPokeyNum(cardNumberOfLeft, cardNumberOfRight);

		break;

	// 开始出牌了
	case MessageType.START_OUT_CARD:
		// 开局时，清除托管状态，确保状态无误
		dataStorage.set(OtherThing.isManaged, "false");
		// 标记游戏正在进行中
		dataStorage.set(OtherThing.isGameOnGoing, "true");

		console.log("开始出牌---当前地主是" + jsObject.playerId);
		if($(".toolTrusteeship").hasClass("gay")){
			$(".toolTrusteeship").removeClass("gay");
			$(".toolMenu").addClass("gay");
		}
		if (jsObject.playerId == getMyPlayerId()) {
			setTimeout(function(){
				my.getBottomPoker(getNumArray(dataStorage.get(
						OtherThing.bottomCards).split(","))); // 显示底牌
				my.button().put(true,function(){
					gameOnTimeOutOnOutCard();
					player.showTrusteeship("my");
				}); // 显示出牌按钮
				
			},3000)
			
		} else {
			toolBar.getBottomPokey(getNumArray(dataStorage.get(
					OtherThing.bottomCards).split(","))); // 显示底牌
			if (dataStorage.get(LeftPlayer.playerId) == jsObject.playerId) {
				// left.wait(); //调用UI方法显示倒计时闹钟
				player.countdown("left");
			} else {
				// right.wait();
				player.countdown("right");
			}
		}
		break;

	// 出牌失败
	case MessageType.OUT_CARD_FAILED:
		//player.msg("my", "text-noAccord");
		player.systemMsg("text-noAccord");
		break;

	// 某人出牌了
	case MessageType.OUT_CARD_SUCC:
		// 清除倒计时
		player.hideCountdown();
		if (jsObject.playerId == getMyPlayerId()) {
			console.log("jsObject.isPlayerPass : " + jsObject.isPlayerPass);
			if (jsObject.isPlayerPass) {
				console.log("我出牌:不出");
				player.msg("my", "text-noPut");
			} else {
				my.trusteePut(jsObject.cards.split("-"));// 显示我出的牌
			}
		} else {
			if (dataStorage.get(LeftPlayer.playerId) == jsObject.playerId) {
				if (jsObject.isPlayerPass) {
					player.msg("left", "text-noPut"); // 调用UI显示左边(上家)玩家“不出牌”提示信息
				} else {
					player.put("left", jsObject.cards.split("-"));
					// 左边(上家)玩家出牌前剩余的牌数
					var perRemainNum = dataStorage.get(LeftPlayer.cardNumber);
					// 存储左边(上家)玩家出牌后还剩余的牌数
					dataStorage.set(LeftPlayer.cardNumber, perRemainNum
							- jsObject.cards.split("-").length);
				}
				// 显示左边玩家手牌的张数
				player.setInfo().pokeyNum("left",
						dataStorage.get(LeftPlayer.cardNumber));
			} else {

				if (jsObject.isPlayerPass) {
					player.msg("right", "text-noPut");
				} else {
					player.put("right", jsObject.cards.split("-"));
					// 右边玩家出牌前剩余的牌数
					var perRemainNum = dataStorage.get(RightPlayer.cardNumber);
					// 存储右边玩家出牌后还剩余的牌数
					dataStorage.set(RightPlayer.cardNumber, perRemainNum
							- jsObject.cards.split("-").length);
				}
				// 显示左边玩家手牌的张数
				player.setInfo().pokeyNum("right",
						dataStorage.get(RightPlayer.cardNumber));
			}
		}
		break;

	// 轮到某人出牌了
	case MessageType.TURN_TO_OUT_CARD:
		if (jsObject.playerId == getMyPlayerId()) {
			player.hideMsg("my"); // 隐藏提示信息
			player.clearPut("my"); // 隐藏自己上一手出牌的结果
			// 是否是我新一轮出牌
			if (jsObject.isStartFromMe) {
				dataStorage.set(OtherThing.perOutCards, null);
			} else {
				dataStorage.set(OtherThing.perOutCards, jsObject.perOutCards
						.split("-")); // 存储上手牌，用于出牌时规则校验
				console
						.log("轮到某人出牌了,上一手牌:  "
								+ jsObject.perOutCards.split("-"));
			}
			// 如果处于非托管状态，则显示出牌按钮
			if (dataStorage.get(OtherThing.isManaged) === undefined
					|| dataStorage.get(OtherThing.isManaged) == "false") {
				if (jsObject.autoQuickPass) {
					 player.systemMsg("text-noBig");
					
					 /*$().alert({
						"content" : "没有大得过大家的牌"
					});*/
					// 自动过
					setTimeout(gameOnNotOutCard, 200);
				} else {
					// 在我头像下显示出牌倒计时闹钟,显示出牌按钮
					
					
					my.button().put(jsObject.isStartFromMe,function(){
						gameOnTimeOutOnOutCard();
						player.showTrusteeship("my");
					}); // 30s超时直接不出
				}
			}
		} else {
			if (dataStorage.get(LeftPlayer.playerId) == jsObject.playerId) {
				player.hideMsg("left");
				player.clearPut("left");
				player.countdown("left"); // 调用UI方法显示倒计时闹钟
			} else {
				player.hideMsg("right");
				player.clearPut("right");
				player.countdown("right"); // 调用UI方法显示倒计时闹钟
			}
		}
		break;

	// 游戏结束
	case MessageType.GAME_OVER:
		// 乐豆显示
		var playersChipsArr = jsObject.playersChips.split(",");
		var remainCardsArr = jsObject.remainCards.split(";");
		var playersWinChipsCountArr = jsObject.playersWinChipsCount.split(",");
		console.log("remainCardsArr : " + remainCardsArr);
		var mySit = Number(dataStorage.get(MyOwner.sit));
		var myWinChipsCount = 0;
		var rightWinChipsCount = 0;
		var leftWinChipsCount = 0;

		// gameModeType游戏模式
		if (jsObject.gameModeType == GameModeType.MODE_TYPE_MATCH) {// 2为比赛场
			toolBar.showGameRankInfo();// 显示打满局数区域
			toolBar.setGameRankInfo(jsObject.myMatchCount,
					jsObject.maxMatchCount);// 显示数值
		}

		// 显示玩家乐筹码和剩余手牌
		for ( var i = 0; i < playersChipsArr.length; i++) {
			if (mySit == i) {
				player.setInfo().dou("my", playersChipsArr[i]);
				if (remainCardsArr[i].length > 0) {
					player.putOther("my", getNumArray(remainCardsArr[i].split("-")));
				}
				myWinChipsCount = playersWinChipsCountArr[i];
			} else {
				if (isOnMyRight(mySit, i)) {
					player.setInfo().dou("right", playersChipsArr[i]);
					if (remainCardsArr[i].length > 0) {
						player.putOther("right", getNumArray(remainCardsArr[i]
								.split("-")));
					}
					rightWinChipsCount = playersWinChipsCountArr[i];
				} else {
					player.setInfo().dou("left", playersChipsArr[i]);
					if (remainCardsArr[i].length > 0) {
						player.putOther("left", getNumArray(remainCardsArr[i]
								.split("-")));
					}
					leftWinChipsCount = playersWinChipsCountArr[i];
				}
			}
		}
		// 清除加倍数
		dataStorage.reset(); // 游戏结束标识位置为取消托管
		dataStorage.set(OtherThing.isGameOnGoing, "false");// 标记游戏非进行中
		player.hideTrusteeship("my"); // 隐藏托管按钮
		player.hideMsg("my"); // 隐藏提示信息
		player.hideMsg("left");
		player.hideMsg("right");

		var obj = {};
		console.log("结算信息："+jsObject);
		obj.myWinCandyCount = jsObject.myWinCandyCount;
		obj.myWinStarCount = jsObject.myWinStarCount;


		if (jsObject.playerId == getMyPlayerId()) {
			if (jsObject.isLandlordWin) { // 是否是地主赢了
				pokeyEffect.bossWin(obj); // 结算结果显示
				console.log("boss拜");
			} else {
				pokeyEffect.bossLose(obj);
				console.log("BOSS胜");
			}
		} 
		break;
	// 活动送乐豆
	case MessageType.REWARD_BEAN_FUN:
		// var rewardBeanFun = jsObject.rewardBeanFunCount;
		var msg = jsObject.msg;
		var currBeanFunCount = jsObject.currBeanFunCount;
		player.setInfo().dou("my", currBeanFunCount);

		// 提示用户
		$().alert({
			"content" : msg
		});
		break;
	// 聊天消息
	case MessageType.CHAT_MESSAGE:
		if (jsObject.playerId == getMyPlayerId()) {
			player.talk("my", jsObject.content);
		} else {
			if (dataStorage.get(LeftPlayer.playerId) == jsObject.playerId) {
				player.talk("left", jsObject.content);
			} else {
				player.talk("right", jsObject.content);
			}
		}
		break;

	// 某用户网络连接中断
	case MessageType.NET_INTERRUPTED:
		var otherTip = "text-downline";
		if (dataStorage.get(LeftPlayer.playerId) == jsObject.playerId) {
			// 显示提示信息
			player.msg("left", otherTip);
			// 隐藏逃跑人的信息
			// player.hideInfo().all("left");
		} else if (dataStorage.get(RightPlayer.playerId) == jsObject.playerId) {
			player.msg("right", otherTip);
			// player.hideInfo().all("right");
		} else {
			player.msg("my", otherTip);
		}
		break;

	// 某用户进入托管状态
	case MessageType.MANAGED_SUCC:
		if (jsObject.playerId == getMyPlayerId()) {
			player.showTrusteeship("my"); // 在我的牌旁边显示托管机器人
		} else {
			if (dataStorage.get(LeftPlayer.playerId) == jsObject.playerId) {
				player.showTrusteeship("left"); // 在左边玩家的牌旁边显示托管机器人
			} else {
				player.showTrusteeship("right"); // 在右边玩家的牌旁边显示托管机器人
			}
		}
		break;

	// 某用户取消托管状态
	case MessageType.UNMANAGED_SUCC:
		if (jsObject.playerId == getMyPlayerId()) {
			player.hideTrusteeship("my"); // 在我的牌旁边取消托管机器人
		} else {
			if (dataStorage.get(LeftPlayer.playerId) == jsObject.playerId) {
				player.hideTrusteeship("left"); // 在左边玩家的牌旁边取消托管机器人
			} else {
				player.hideTrusteeship("right"); // 在右边玩家的牌旁边取消托管机器人
			}
		}
		break;

	// 出牌提示成功
	case MessageType.OUTCARD_SUGGESTION_SUCC:
		if (jsObject.isPass) { // 是否提示“不出牌”
			/*$().alert({
				"content" : "建议不出"
			});*/
			player.systemMsg("text-reNoPut");
		} else if (jsObject.cards.length > 0) {
			my.selectPokey(jsObject.cards.split("-"));
		} else {
			console.log("提示没能取到牌！");
		}
		break;

	// 询问农民是否翻倍（是否踢），线性的，先右后左
	case MessageType.ASK_FARMER_DOUBLE:
		// 在该农民头像旁边显示“踢”、“不踢”按钮
		gameFarmerDouble(false);
		break;

	// 农民选择的结果，是否翻倍（是否踢），广播所有玩家
	case MessageType.RESULT_FARMER_DOUBLE:
		if (jsObject.playerId == getMyPlayerId()) {
			if (jsObject.doubleFlag) {
				player.setInfo().multiple("my", 2);
				player.msg("my", "text-double");
			} else {
				player.msg("my", "text-noDouble");
			}
		} else {
			if (dataStorage.get(LeftPlayer.playerId) == jsObject.playerId) {
				if (jsObject.doubleFlag) {
					player.setInfo().multiple("left", 2);
					player.msg("left", "text-double");
				} else {
					player.msg("left", "text-noDouble");
				}
			} else {
				if (jsObject.doubleFlag) {
					player.setInfo().multiple("right", 2);
					player.msg("right", "text-double");
				} else {
					player.msg("right", "text-noDouble");
				}
			}
		}
		break;

	// 询问地主是否翻倍（是否反踢）,该消息，只当我为地主是，才会收到
	case MessageType.ASK_LANDLORD_DOUBLE:
		console.log("询问地主是否翻倍,发起加倍（踢）的农民：" + jsObject.playerId);
		gameLandlordDouble(false, jsObject.playerId);
		break;

	// 地主选择的结果，是否翻倍（是否拉）
	case MessageType.RESULT_LANDLORD_DOUBLE:
		if (jsObject.playerId == getMyPlayerId()) {
			player.hideMsg("my");
			if (jsObject.doubleFlag) {
				player.setInfo().multiple("my", 4);
			}
		} else {
			if (dataStorage.get(LeftPlayer.playerId) == jsObject.playerId) {
				player.hideMsg("left");
				if (jsObject.doubleFlag) {
					player.setInfo().multiple("left", 4);
				}
			} else {
				player.hideMsg("right");
				if (jsObject.doubleFlag) {
					player.setInfo().multiple("right", 4);
				}
			}
		}
		break;
	// 无需重联
	case MessageType.NOT_NEED_RECONNECT:
		console.log("没有未打玩的牌局，无需重联");
		callbackOnNoNeedReconnect();
		break;
	// 上盘牌未打完，恢复牌局
	case MessageType.NEED_RECONNECT:
		console.log("上盘牌未打完，恢复牌局");
		restorePlayerBox(jsObject);
		break;

	// 被踢出房间，需要返回游戏大厅
	case MessageType.KICKED_OUT:
		/*$().alert({
			content : "由于玩家长时间没有操作，牌局被解散"
		});*/
		player.systemMsg("text-dissolve");
		room.switchToRoom();
		break;
	// 系统单点通知消息
	case MessageType.PERSONAL_MSG:
		$().alert({
			content : jsObject.content
		});
		break;
	case MessageType.RECONNECT_SUCC:
		/*$().alert({
			content : jsObject.playerId + "网络重连成功"
		});*/
		player.systemMsg("text-reconnect");
		console.log(jsObject.playerId + "网络重连成功");
		break;
	case MessageType.SYSTEM_MSG:
		$().broadcast({
			content : jsObject.content
		});
		break;
	case MessageType.GET_FORCE_OUT:
		console.log(111);
		room.goin();
		break;
		/*道具使用成功*/	
	case MessageType.USE_ITEM_SUCC:
		console.log("道具使用成功");
		$().alert({
			content : "道具已使用"
		});
		break;
	/*道具使用失败*/	
	case MessageType.USE_ITEM_FAIL:
		console.log("道具使用失败");
		$().alert({
			content : "道具使用失败"
		});
		break;
		
		/*发送报名人数消息*/	
	case MessageType.USE_SIGNUP_NUMBER:
		console.log("发送报名人数消息");
		console.log(jsObject);
		require(["js/mGame.js"], function(game){ 
			game.gameNowNums(jsObject.signUpNumber);
		});
		break;
		
		/*比赛场发送比赛结果*/	
	case MessageType.USE_GAME_OVER:
		console.log("比赛场发送比赛结果");
		break;
		
		/*开启第二号房间*/	
	case MessageType.OPENING_ROOM_102:
		
		break;
		/*开启第三号房间*/	
	case MessageType.OPENING_ROOM_103:
		
		break;
		/*开启第四号房间*/	
	case MessageType.OPENING_ROOM_104:
		
		break;
		/*开启第五号房间*/	
	case MessageType.OPENING_ROOM_105:
		
		break;
		
		/*开启第二号Boss*/	
	case MessageType.OPENING_BOOS_102:
		$().alert({
			content : "开启第二号Boss"
		});
		require(["js/mEffect.js"], function(effect){  
			effect.openBoss();
		});
		break;
		/*开启第三号Boss*/	
	case MessageType.OPENING_BOOS_103:
		$().alert({
			content : "开启第三号Boss"
		});
		require(["js/mEffect.js"], function(effect){  
			effect.openBoss();
		});
		break;
		
		/*开启初级比赛场*/	
	case MessageType.OPENING_COMPETITION_101:
		$().alert({
			content : "开启初级比赛场"
		});
		require(["js/mEffect.js"], function(effect){  
			effect.openCompetition();
		});
		break;
		/*开启中级比赛场*/	
	case MessageType.OPENING_COMPETITION_102:
		$().alert({
			content : "开启中级比赛场"
		});
		require(["js/mEffect.js"], function(effect){  
			effect.openCompetition();
		});
		break;
		/*开启高级比赛场*/	
	case MessageType.OPENING_COMPETITION_103:
		$().alert({
			content : "开启高级比赛场"
		});
		require(["js/mEffect.js"], function(effect){  
			effect.openCompetition();
		});
		break;
		
		/*开启乐斗场*/	
	case MessageType.OPENING_BEANFUN_BATTLE:
		$().alert({
			content : "开启乐斗场"
		});
		require(["js/mEffect.js"], function(effect){  
			effect.openBeanfun();
		});
		break;
		
	case MessageType.ERROR:
		/** socket通讯错误 1 尚未登录 */
		/** socket通讯错误 2 尚未入桌 */
		/** socket通讯错误 3 非法的userId */
		if (jsObject.code == 1) {
			// TODO 暂时执行刷新动作
			window.location.href = getServiceURL() + "/index.jsp?"
					+ (new Date()).getTime();
		}
		console.log("socket通讯错误  -> code=" + ejsObject.code + " msg="
				+ jsObject.msg);
		break;
	default:
		console.log("default  丢弃消息  -> " + event.data);
		break;
	}
}

// 没有未打玩的牌局，无需重联
function callbackOnNoNeedReconnect() {
	// 离开桌子
	room.switchToRoom();
}

// 上盘牌未打完，恢复牌局
function restorePlayerBox(jsObj) {
	// 1.切换视图到桌子
	$("#room").hide();
	$("#playBox").show();
	$("body").attr("class","playBg");
	// 2.重置UI
	room.resetDesk();
	// 3.重置状态
	initGame();
	my.goin();

	// 4.恢复状态
	var deskSnapshot = jsObj.deskSnapshot;

	// 牌桌顶部基分
	player.setBaseScore(deskSnapshot.baseScore);

	// 存储当前用户信息
	dataStorage.set(MyOwner.playerId, deskSnapshot.myPlayerId);
	dataStorage.set(MyOwner.sit, deskSnapshot.mySit); // 座位号

	// gameModeType游戏模式
	if (deskSnapshot.gameModeType == GameModeType.MODE_TYPE_MATCH) {// 2为比赛场
		toolBar.showGameRankInfo();// 显示打满局数区域
		toolBar.setGameRankInfo(deskSnapshot.myMatchCount, deskSnapshot.maxMatchCount);// 显示数值
	}

	// 恢复所有玩家的信息
	var playersInfo = deskSnapshot.playersInfo;
	for ( var i = 0; i < playersInfo.length; i++) {
		var doubleCount = 0;
		if (isOnMyRight(deskSnapshot.landlordSit, playersInfo[i].sit)) {
			doubleCount = deskSnapshot.rightFarmerDoubleCount;
		} else if (isOnMyLeft(deskSnapshot.landlordSit, playersInfo[i].sit)) {
			doubleCount = deskSnapshot.leftFarmerDoubleCount;
		}
		
		var nickName = playersInfo[i].roleName;
		var chipsCount = playersInfo[i].beanFunCount;
		var role = playersInfo[i].roleResourceName;
		var star = playersInfo[i].star;
		var candy = playersInfo[i].candy;
		var score = playersInfo[i].score;
		if(deskSnapshot.gameModeType == GameModeType.MODE_TYPE_MATCH){
			chipsCount = playersInfo[i].matchChipsCount;
		}

		console.log("doubleCount -> " + doubleCount);

		if (playersInfo[i].playerId == getMyPlayerId()) {
			// 显示右边玩家的昵称和乐豆数
			player.goin("my", {
				"name" : nickName,
				"dou" : chipsCount,
				"role":role,
				"star":star,
				"candy":candy,
				"score":score
			});
			dataStorage.set(MyOwner.cardNumber, playersInfo[i].handCardCount);// 存储自身牌数
			player.setInfo()
					.pokeyNum("my", dataStorage.get(MyOwner.cardNumber));// 显示牌数
			/*还原头像*/
			var rolePeopleHead = dataStorage.get(MyOwner.rolePeopleHead);
			player.setInfo().peopleHead("my",role,rolePeopleHead);

			// 显示加倍数
			if (Number(doubleCount) > 0) {
				player.setInfo().multiple("my", doubleCount);
			}
		} else {
			if (isOnMyRight(getMySit(), playersInfo[i].sit)) {
				// 显示右边玩家的昵称和乐豆数
				player.goin("right", {
					"name" : nickName,
					"dou" : chipsCount,
					"role":role,
					"star":star,
					"candy":candy,
					"score":score
				});

				// 存储玩家右手边的用户信息
				dataStorage.set(RightPlayer.playerId, playersInfo[i].playerId);
				dataStorage.set(RightPlayer.sit, playersInfo[i].sit);
				dataStorage.set(RightPlayer.cardNumber,
						playersInfo[i].handCardCount);// 存储牌数
				player.setInfo().pokeyNum("right",
						dataStorage.get(RightPlayer.cardNumber));// 显示牌数
				/*还原头像*/
				var rolePeopleHead = dataStorage.get(RightPlayer.rolePeopleHead);
				player.setInfo().peopleHead("right",role,rolePeopleHead);

				// 显示加倍数
				if (Number(doubleCount) > 0) {
					player.setInfo().multiple("right", doubleCount);
				}
			} else {
				// 显示左边玩家的昵称和乐豆数
				player.goin("left", {
					"name" : nickName,
					"dou" : chipsCount,
					"role":role,
					"star":star,
					"candy":candy,
					"score":score
				});

				// 存储玩家左手边的用户信息
				dataStorage.set(LeftPlayer.playerId, playersInfo[i].playerId);
				dataStorage.set(LeftPlayer.sit, playersInfo[i].sit);
				dataStorage.set(LeftPlayer.cardNumber,
						playersInfo[i].handCardCount);// 存储牌数
				player.setInfo().pokeyNum("left",
						dataStorage.get(LeftPlayer.cardNumber));// 显示牌数
				/*还原头像*/
				var rolePeopleHead = dataStorage.get(LeftPlayer.rolePeopleHead);
				player.setInfo().peopleHead("left",role,rolePeopleHead);

				// 显示加倍数
				if (Number(doubleCount) > 0) {
					player.setInfo().multiple("left", doubleCount);
				}
			}
		}
	}

	// 设置自己的牌
	var cardsArr = deskSnapshot.myCards.split("-");
	my.reGet(cardsArr, deskSnapshot.state == Desk.STATE_ON_OUT_CARD);// 显示牌，无特效

	var timerStartTimeStamp = deskSnapshot.timerStartTimeStamp;
	var currentTime = new Date().getTime();
	var timeout = 30 - Math.floor((currentTime - timerStartTimeStamp) / 1000);
	console.log("倒计时：" + currentTime + "-" + timerStartTimeStamp + "="
			+ timeout + "秒");

	if (timeout > 30) {
		timeout = 30;
	}
	if (timeout < 0) {
		timeout = 0;
	}

	if (deskSnapshot.state == Desk.STATE_ON_GRAB_LANDLORD) {// 正在抢地主
		askGrabLandlord(deskSnapshot.currentPlayerToGrabLandlord,
				Number(deskSnapshot.grabLandlordBetMin), timeout);
	} else {
		// 设置地主
		setResultOfGrabLandlord(deskSnapshot.landlordPlayerId);

		if (deskSnapshot.state == Desk.STATE_ON_DOUBLE) {// 正在加倍
			if (deskSnapshot.currentPlayerToDouble == getMyPlayerId()) {
				// 如果我是地主
				if (deskSnapshot.landlordPlayerId == getMyPlayerId()) {
					console.log("询问地主是否翻倍,发起加倍（踢）的农民："
							+ deskSnapshot.doubleTargetFarmer);
					
					gameLandlordDouble(false,deskSnapshot.doubleTargetFarmer);
						
				} else {
					// 在该农民头像旁边显示“踢”、“不踢”按钮
					console.log("询问农民加倍：" + deskSnapshot.landlordPlayerId);
					
					gameFarmerDouble(false);
					
				}
			}
		} else if (deskSnapshot.state == Desk.STATE_ON_OUT_CARD) {// 正在出牌
			// 底牌存储
			var bottomCards = deskSnapshot.bottomCards.split("-");
			dataStorage.set(OtherThing.bottomCards, bottomCards);
			toolBar.getBottomPokey(getNumArray(bottomCards)); // 显示底牌

			// 进入托管状态
			player.showTrusteeship("my");
		}
	}

	$(".landlordLoad").remove();
	$("#room").hide();
	$("#playBox").show();

}

// 进入托管状态
function requestManaged() {
	console.log("进入托管状态");
	dataStorage.set(OtherThing.isManaged, true);
	gameOnRequestManaged();
}

// 取消托管状态
function requestUnmanaged() {
	console.log("取消托管状态");
	dataStorage.set(OtherThing.isManaged, false);
	gameOnRequestUnmanaged();
}

// 加倍、不加倍
function gameDouble(doubleFlag, playerId) {
	if (dataStorage.get(MyOwner.isLandlord) == "true") {
		gameLandlordDouble(doubleFlag, playerId); // 地主选择
	} else {
		gameFarmerDouble(doubleFlag); // 农民选择
	}
}
// 询问抢地主
function askGrabLandlord(playerId, grabLandlordBetMin, timeout) {
	timeout = timeout || 30;
	if (playerId == getMyPlayerId()) {
		var grabLandlordBetMin = Number(grabLandlordBetMin);
		console.log("询问否抢地主, grabLandlordBetMin = " + grabLandlordBetMin);
		//my.button().bid(grabLandlordBetMin, function() {
			gameOnGrabLandLord(3);
		//}, timeout); // 30s超时后直接不抢
		player.hideMsg("left");
	} else {
		if (dataStorage.get(LeftPlayer.playerId) == playerId) {
			player.countdown("left");
			player.hideMsg("right");
		} else {
			player.countdown("right");
		}
	}
}

// 设置抢地主结果
function setResultOfGrabLandlord(playerId) {
	console.log("抢地主结果---当前地主是" + playerId);

	var isRightLandlord = dataStorage.get(RightPlayer.playerId) == playerId;
	var isLeftLandlord = dataStorage.get(LeftPlayer.playerId) == playerId;
	var isMyLandlord = getMyPlayerId() == playerId;

	dataStorage.set(MyOwner.isLandlord, isMyLandlord);// 存储我是地主
	dataStorage.set(LeftPlayer.isLandlord, isLeftLandlord);// 存储左边是地主
	dataStorage.set(RightPlayer.isLandlord, isRightLandlord);// 存储右边是地主

	player.setInfo().head("right", isRightLandlord);// 显示地主头像
	player.setInfo().head("my", isMyLandlord);
	player.setInfo().head("left", isLeftLandlord);

}
// 保存并显示玩家的手牌数
function setPokeyNum(cardNumberOfLeft, cardNumberOfRight) {
	// 存储牌数
	dataStorage.set(LeftPlayer.cardNumber, cardNumberOfLeft);
	dataStorage.set(RightPlayer.cardNumber, cardNumberOfRight);
	// 显示牌数
	player.setInfo().pokeyNum("left", dataStorage.get(LeftPlayer.cardNumber));
	player.setInfo().pokeyNum("right", dataStorage.get(RightPlayer.cardNumber));
}

// 房间显示时，刷新相关数据
function onRoomShow() {
	var url = getServiceURL() + "/popup/user?userId=" + getMyUserId() + "&"
			+ (new Date()).getTime();
	$.ajax({
		url : url,
		dataType:"json",
		success : function(data) {
			var data = data.data.userInfo;
			var nickName = data.roleName;
			var beanfun = data.beanfun;
			require(["js/mCard.js"], function(card){ 
				$("#user-dou").html(beanfun);
				card.setRoom(beanfun);
			});
			$("#user-nickname").html(nickName);

		}
	});
}

//排行榜请求
function  gameUserBillboard(userId){
	$.getJSON("popup/billboardList?userId="+userId, function(data){
		var tt = "";
        $.each(data, function(k, v) {
            $.each(v,function(kk, vv) {
                tt += kk + "：" + vv + "<br/>";
                console.log("排行榜返回的json数据: " + tt);
            });
        });
	})
}
//进房间
function enterRoom(roomId) {
	Game.ajax({
	    url: getServiceURL() + "/room/enter?roomId=" + roomId,
	    dataType: "json",
	    success: function(data1) {
	    	if (data1.success) {
	        room.desk(roomId);
	      } else {
	        $().alert({
	          "content": data1.message
	        });
	      }
	     // room.createRoom();
	    }
	});
}
// 获取连续登录天数
function gameContinLoginCount(userId){
	var url = "popup/continLoginCount?userId="+userId;
	$.getJSON(url, function(data){
		//调用UI方法
		//msgBox.sendDou(data.count, userId);
	})
}

// 领取乐豆
function gameReceiveFreeBeanFun(continLoginCount, userId){
	var url = "popup/receiveFreeBeanFun?continLoginCount="+continLoginCount+"&userId="+userId+"&"+(new Date()).getTime();
	$.getJSON(url, function(data){
			  // 将返回的json数据序列化成js对象
			  if(data.receiveBeanFunFlag == 1){
				  onRoomShow();  // 刷新大厅乐豆数据
				  $().alert({"content":"领取成功！"});
				  console.log("乐豆领取成功...");
			  }else{
				  $().alert({"content":"今天乐豆已领取！"});
				  console.log("今天乐豆已领取....");
			  }
		})
};
//房间,G是游戏共用类,实现名叫:Game
(function($,G){
	window.Room={
		signUp:function(roomId){
			G.ajax({
				url : G.getBaseURL() + "/room/signUp?roomId=" + roomId,
				dataType : "json",
				success : function(data) {
					var room = data.data;
					if (data.success) {
						$("#signUpNumber_" + roomId).html(
								room.signUpNumber + "");
						onRoomShow();
					}
					$().alert({
						content : data.message
					});
				}
			});
		}
	};
})($, Game);